﻿using BLL;
using Model;
using System.Web.Security;
using System.Web;

namespace System.Web.Mvc
{
    /// <summary>
    /// URL授权类
    /// </summary>
    public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        public bool CheckRole = true;
        /// <summary>
        /// 重写OnAuthorization
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            Sys_ActionsInControllersInRoles_BLL _Sys_ActionsInControllersInRoles_BLL = new Sys_ActionsInControllersInRoles_BLL();
            Sys_Users_Logs_BLL _Sys_Users_Logs_BLL = new Sys_Users_Logs_BLL();
            Sys_Users_BLL _Sys_Users_BLL = new Sys_Users_BLL();

            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (CheckRole)
                {
                    string ControllerName = filterContext.RouteData.Values["controller"].ToString();
                    string ActionName = filterContext.RouteData.Values["action"].ToString();

                    if (!_Sys_ActionsInControllersInRoles_BLL.Check(ActionName, ControllerName, new Guid(filterContext.HttpContext.User.Identity.Name)))
                    {
                        Error(filterContext);
                    }

                    //记录用户操作
                    var log = new Sys_Users_Logs() { Content = filterContext.HttpContext.Request.Url.AbsolutePath };
                    _Sys_Users_Logs_BLL.Save(null, ref log);
                }

            }
            else
            {
                //use the current url for the redirect
                string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;

                //send them off to the login page
                string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
                string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
                filterContext.HttpContext.Response.Redirect(loginUrl, true);
            }
        }

        private void Error(AuthorizationContext filterContext)
        {
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.Write("没有权限！");
            filterContext.HttpContext.Response.End();

        }
    }
}
